<?php

namespace Sms\Driver;

class Alidayu implements Sms
{
    private $client;
    private $sign;
    private $error;

    function __construct($config)
    {
        require('dependents/alidayu/TopSdk.php');
        $this->client = new \TopClient();
        $this->client->appkey    = $config['APP_KEY'];
        $this->client->secretKey = $config['APP_SECRET'];
        $this->sign              = $config['DEFAULT_SIGN'];
    }

    public function send($rec_num, $tpl_code, array $params)
    {
        // vendor('alidayu.TopSdk');
        $params = $this->toStrArray($params);
        $req = new \AlibabaAliqinFcSmsNumSendRequest();
        // $req->setExtend('123456');
        $req->setSmsType('normal');
        $req->setSmsFreeSignName($this->sign);
        $req->setSmsParam(json_encode($params));
        $req->setRecNum($rec_num);
        $req->setSmsTemplateCode($tpl_code);
        $resp = $this->client->execute($req);
        if (isset($resp->code)) {
            $this->error = $resp->sub_code.':'.$resp->sub_msg;
            return false;
        } else {
            return true;
        }
    }

    public function getError()
    {
        return $this->error;
    }

    /**
     * 将数组里的元素转为字符串
     * @param  array  $array 参数
     * @return array  转换后的array
     */
    private function toStrArray(array $array)
    {
        return array_map(function($val) {
            return strval($val);
        }, $array);
    }
}
